package com.demo.las.service;

import com.demo.las.entity.KnowledgeAsset;
import com.demo.las.repository.KnowledgeAssetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class KnowledgeAssetService {

    @Autowired
    private KnowledgeAssetRepository knowledgeAssetRepository;

    public KnowledgeAsset createKnowledgeAsset(KnowledgeAsset knowledgeAsset) {
        return knowledgeAssetRepository.save(knowledgeAsset);
    }

    public Optional<KnowledgeAsset> getKnowledgeAssetById(Long id) {
        return knowledgeAssetRepository.findById(id);
    }

    public List<KnowledgeAsset> getKnowledgeAssetsByUser(Long userId) {
        return knowledgeAssetRepository.findByUserIdOrderByAssetValueDesc(userId);
    }

    public Optional<KnowledgeAsset> getKnowledgeAssetByUserAndSubject(Long userId, String subject) {
        return knowledgeAssetRepository.findByUserIdAndSubject(userId, subject);
    }

    public List<KnowledgeAsset> getKnowledgeAssetsByMasteryLevel(Long userId, BigDecimal minMasteryLevel) {
        return knowledgeAssetRepository.findByUserIdAndMasteryLevelGreaterThan(userId, minMasteryLevel);
    }

    public BigDecimal getTotalAssetValue(Long userId) {
        BigDecimal total = knowledgeAssetRepository.getTotalAssetValueByUser(userId);
        return total != null ? total : BigDecimal.ZERO;
    }

    public BigDecimal getTotalCurrentValue(Long userId) {
        BigDecimal total = knowledgeAssetRepository.getTotalCurrentValueByUser(userId);
        return total != null ? total : BigDecimal.ZERO;
    }

    public BigDecimal getAverageMasteryLevel(Long userId) {
        BigDecimal avg = knowledgeAssetRepository.getAverageMasteryLevelByUser(userId);
        return avg != null ? avg : BigDecimal.ZERO;
    }

    public List<Object[]> getMasteryLevelBySubject(Long userId) {
        return knowledgeAssetRepository.getMasteryLevelBySubject(userId);
    }

    public List<Object[]> getAssetOverviewByUser(Long userId) {
        return knowledgeAssetRepository.getAssetOverviewByUser(userId);
    }

    public List<KnowledgeAsset> getRecentlyStudiedAssets(Long userId) {
        return knowledgeAssetRepository.findRecentlyStudiedAssets(userId);
    }

    public List<KnowledgeAsset> getAssetsNeedReview(Long userId) {
        LocalDate sevenDaysAgo = LocalDate.now().minusDays(7);
        return knowledgeAssetRepository.findAssetsNeedReview(userId, sevenDaysAgo);
    }

    public Long countAssetsAboveMasteryLevel(Long userId, BigDecimal minLevel) {
        return knowledgeAssetRepository.countAssetsAboveMasteryLevel(userId, minLevel);
    }

    public KnowledgeAsset updateKnowledgeAsset(KnowledgeAsset knowledgeAsset) {
        return knowledgeAssetRepository.save(knowledgeAsset);
    }

    public void deleteKnowledgeAsset(Long id) {
        knowledgeAssetRepository.deleteById(id);
    }

    /**
     * 更新知识资产（基于学习记录）
     */
    public void updateAssetFromStudyRecord(Long userId, String subject, BigDecimal studyTime, BigDecimal efficiencyScore, BigDecimal qualityScore) {
        Optional<KnowledgeAsset> existingAsset = getKnowledgeAssetByUserAndSubject(userId, subject);
        
        KnowledgeAsset asset;
        if (existingAsset.isPresent()) {
            asset = existingAsset.get();
            // 更新总学习时长
            asset.setTotalHours(asset.getTotalHours().add(studyTime));
            // 更新掌握程度（基于有效学习时间）
            BigDecimal effectiveTime = studyTime.multiply(efficiencyScore).multiply(qualityScore);
            BigDecimal newMasteryLevel = asset.getMasteryLevel().add(effectiveTime.divide(BigDecimal.valueOf(10), 2, BigDecimal.ROUND_HALF_UP));
            if (newMasteryLevel.compareTo(BigDecimal.valueOf(100)) > 0) {
                newMasteryLevel = BigDecimal.valueOf(100);
            }
            asset.setMasteryLevel(newMasteryLevel);
            asset.setLastStudyDate(LocalDate.now());
        } else {
            // 创建新的知识资产
            asset = new KnowledgeAsset();
            asset.setUserId(userId);
            asset.setSubject(subject);
            asset.setTotalHours(studyTime);
            asset.setLastStudyDate(LocalDate.now());
            
            // 计算初始掌握程度
            BigDecimal effectiveTime = studyTime.multiply(efficiencyScore).multiply(qualityScore);
            BigDecimal initialMasteryLevel = effectiveTime.divide(BigDecimal.valueOf(10), 2, BigDecimal.ROUND_HALF_UP);
            if (initialMasteryLevel.compareTo(BigDecimal.valueOf(100)) > 0) {
                initialMasteryLevel = BigDecimal.valueOf(100);
            }
            asset.setMasteryLevel(initialMasteryLevel);
        }
        
        // 计算资产价值
        asset.setAssetValue(asset.getTotalHours().multiply(BigDecimal.valueOf(50)));
        asset.setAcquisitionCost(asset.getTotalHours().multiply(BigDecimal.valueOf(40)));
        asset.setCurrentValue(asset.getAssetValue().multiply(asset.getMasteryLevel()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
        
        knowledgeAssetRepository.save(asset);
    }
}
